package com.insight.entity;

import com.insight.common.enums.ChangeType;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * T052: 元数据版本实体类
 * 记录表元数据的版本历史和变更信息
 *
 * @author Insight Team
 */
@Entity
@Table(name = "metadata_version",
        indexes = {
                @Index(name = "idx_metadata_version_table", columnList = "table_id"),
                @Index(name = "idx_metadata_version_number", columnList = "version_number"),
                @Index(name = "idx_metadata_version_change_type", columnList = "change_type"),
                @Index(name = "idx_metadata_version_created_at", columnList = "created_at")
        })
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MetadataVersion {

    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 关联的表
     */
    @NotNull(message = "所属表不能为空")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "table_id", nullable = false)
    private MetadataTable table;

    /**
     * 版本号 (从1开始递增)
     */
    @NotNull(message = "版本号不能为空")
    @Column(name = "version_number", nullable = false)
    private Integer versionNumber;

    /**
     * 变更类型 (ADDED, MODIFIED, DELETED)
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "change_type", length = 20)
    private ChangeType changeType;

    /**
     * 变更描述
     */
    @Column(name = "change_description", length = 2000)
    private String changeDescription;

    /**
     * 快照数据 (JSONB格式存储完整的表结构信息)
     * 存储当前版本的完整元数据快照,包括表结构、列定义、索引等
     * 注意: H2测试环境使用JSON类型，生产环境使用jsonb
     */
    @JdbcTypeCode(SqlTypes.JSON)
    @Column(name = "snapshot_data", columnDefinition = "JSON")
    private Map<String, Object> snapshotData;

    /**
     * 创建者
     */
    @Column(name = "created_by", length = 100)
    private String createdBy;

    /**
     * 版本创建时间
     */
    @CreationTimestamp
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    /**
     * 生命周期回调: 持久化之前
     * 设置默认值,避免null
     */
    @PrePersist
    public void prePersist() {
        if (this.changeType == null) {
            this.changeType = ChangeType.MODIFIED;
        }
    }
}
